package org.example.core.security.handler;

import com.alibaba.fastjson2.JSONObject;
import org.apache.catalina.manager.Constants;
import org.example.core.enums.ApiResult;
import org.example.core.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description: 登陆成功处理器
 * Date: 2024/1/28 15:58
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            response.setContentType("application/json;charset="+ Constants.CHARSET);

            response.setHeader("Access-control-Allow-Origin", response.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            response.setHeader("Access-Control-Allow-Headers", response.getHeader("Access-Control-Request-Headers"));
            // 跨域发送一个option请求
            if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
                response.setStatus(HttpStatus.OK.value());
            }
        response.getWriter().write(JSONObject.toJSONString(ApiResult.success(jwtUtil.create(authentication.getPrincipal(), 60 * 60 * 1000))));
    }
}
